const { util, InsideErr, BaseErr } = require("utils");

function request(method) {
    return function (url, baseConfig = {}) {
        return async function (
            payload,
            config = {
                contentType: "json",
            }
        ) {
            let resultConfig = config || {};
            let [err, data] = await util.awaitWrap(
                uniCloud.httpclient.request(url, {
                    method: method,
                    data: payload || {},
                    dataType: "json",
                    ...resultConfig,
                })
            );
            // 解析
            if (!util.nilValue(err)) {
                return [new InsideErr(err), null];
            }
            if (util.nilValue(data)) {
                return [new BaseErr(-3007, "数据为空"), null];
            }
            // 判断是不是要返回 原始值
            let { rawValue } = baseConfig || {};
            let targetData = undefined;
            if (rawValue === true) {
                targetData = data.res || {};
            } else {
                targetData = data.data || {};
            }
            return [null, targetData];
        };
    };
}

// 代理请求
function proxyRequest(method, type = "json") {
    return (url) => {
        return async (payload, headers) => {
            let requestParamArr = [url, payload || {}];
            // post 有2个接口哦
            let fn = "get";
            if (method === "POST") {
                fn = type === "json" ? "postJson" : "postForm";
                // post 可以添加 header参数
                if (typeof headers === "object" && !util.emptyValue(headers)) {
                    requestParamArr.push(headers);
                }
            }

            let [err, data] = await util.awaitWrap(
                uniCloud.httpProxyForEip[fn](...requestParamArr)
            );
            // 解析
            if (!util.nilValue(err)) {
                return [new InsideErr(err), null];
            }
            if (util.nilValue(data)) {
                return [new BaseErr(-3007, "数据为空"), null];
            }
            let targetData = data.data || data.body || {};
            return [null, targetData];
        };
    };
}

const postRequest = request("POST");
const getRequest = request("GET");

// 代理请求
const proxyGetRequest = proxyRequest("GET");
// post有2个类型
const proxyPostRequest = proxyRequest("POST", "form");
const proxyPostJSONRequest = proxyRequest("POST", "json");

module.exports = {
    getRequest,
    postRequest,
    proxyGetRequest,
    proxyPostRequest,
    proxyPostJSONRequest,
};
